package org.mclll.xwangplugin.util;

import com.google.common.collect.Lists;
import org.bukkit.Bukkit;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.mclll.xwangplugin.questTracking.persistence.Persistence;

import java.lang.reflect.Field;
import java.util.*;

import static org.mclll.xwangplugin.questTracking.listener.QuestListener.SCOREBOARD_NAME;

/**
 * @author: geduo
 * @date: 2023/10/14 19:18
 */
public class ScoreBoardUtil {
    public static List<Persistence.SerializeScore> getScore(Scoreboard scoreboard) {
        List<Persistence.SerializeScore> scores = Lists.newArrayList();
        Objective scoreObj = scoreboard.getObjective(SCOREBOARD_NAME);
        for (String entry : scoreboard.getEntries()) {
            scores.add(
                    new Persistence.SerializeScore(entry, scoreObj.getScore(entry).getScore())
            );
        }
        scores.sort(Comparator.comparingInt(Persistence.SerializeScore::getValue));
        Collections.reverse(scores);
        return scores;
    }

    public static Scoreboard copyToScore(Scoreboard source) {
        Scoreboard target = Bukkit.getScoreboardManager().getNewScoreboard();
        try {
            Field boardField = source.getClass().getDeclaredField("board");
            boardField.setAccessible(true);
            Field registeredGloballyField = source.getClass().getDeclaredField("registeredGlobally");
            registeredGloballyField.setAccessible(true);
            Object board = boardField.get(source);
            Class boardSuperclass = board.getClass().getSuperclass();
            Field iField = board.getClass().getDeclaredField("i");
            iField.setAccessible(true);
            Field mField = boardSuperclass.getDeclaredField("m");
            mField.setAccessible(true);
            Field lField = boardSuperclass.getDeclaredField("l");
            lField.setAccessible(true);
            // 设置值
            Object newBoard = boardField.get(target);
            ((ArrayList) iField.get(newBoard)).addAll((List) iField.get(board));
            ((HashMap) lField.get(newBoard)).putAll((HashMap) lField.get(board));
            ((HashMap) mField.get(newBoard)).putAll((HashMap) mField.get(board));
            registeredGloballyField.set(target, registeredGloballyField.get(source));
        } catch (Exception ignore) {
        }
        return target;
    }
}
